package valuecomusa.fijibus.eticket;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import valuecomusa.fijibus.eticket.shorthaul.R;

public class StudentVoucher extends Activity
{
	private RadioButton activeVoucher;
	private double totalFare;
	private double cashBalance;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.student_voucher);
        setResult(RESULT_CANCELED, null);
		//---get input
		Intent input = getIntent();
		//--
		totalFare = input.getDoubleExtra("FARE_AMOUNT", 0);
        if(WorkingSession.getInstance().currentPassenger.CurrentBalance < 0)
            totalFare = totalFare - WorkingSession.getInstance().currentPassenger.CurrentBalance;
		cashBalance = totalFare;
		//---Init value
		TextView tv = (TextView)findViewById(R.id.student_textview_totalfare);
		tv.setText(WorkingSession.getInstance().decimalFormat.format(totalFare));
		//--
		tv = (TextView)findViewById(R.id.student_textview_cash_balance);
		tv.setText(WorkingSession.getInstance().decimalFormat.format(cashBalance));
		//--register event handler		
		RadioButton rb = (RadioButton)findViewById(R.id.student_radio_blue);
		rb.setOnCheckedChangeListener(voucher_CheckChange);
		//--
		rb = (RadioButton)findViewById(R.id.student_radio_yellow);
		rb.setOnCheckedChangeListener(voucher_CheckChange);
		//--
		rb = (RadioButton)findViewById(R.id.student_radio_red);
		rb.setOnCheckedChangeListener(voucher_CheckChange);
		rb.setChecked(true);
		//--
        Button submit = (Button) findViewById(R.id.student_submit);
        submit.setOnClickListener(onSubmitClick);
        //-
        Button cancel = (Button) findViewById(R.id.student_cancel);
        cancel.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                finish();
            }
        });
        //-
        Button cash = (Button) findViewById(R.id.student_voucher_pay_cash);
        cash.setOnClickListener(onCollectCashClick);
        //-
        Button bmf = (Button) findViewById(R.id.student_voucher_pay_bmf);
        bmf.setOnClickListener(onCollectBMFClick);
	}
	
	private CompoundButton.OnCheckedChangeListener voucher_CheckChange = new CompoundButton.OnCheckedChangeListener()
	{			
		@Override
		public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
		{
			if(!isChecked)
				return;
			
			if(activeVoucher != null)
				activeVoucher.setChecked(false);
			activeVoucher = (RadioButton) buttonView;
			
			TextView tv = (TextView)findViewById(R.id.student_red_fare);
			tv.setVisibility(buttonView.getId() == R.id.student_radio_red? View.VISIBLE:View.GONE);
			//--
			tv = (TextView)findViewById(R.id.student_blue_fare);
			tv.setVisibility(buttonView.getId() == R.id.student_radio_blue? View.VISIBLE:View.GONE);
			//--
			tv = (TextView)findViewById(R.id.student_yellow_fare);
			tv.setVisibility(buttonView.getId() == R.id.student_radio_yellow? View.VISIBLE:View.GONE);
			
			CalculateCashBalance();

            if(cashBalance > 0)
            {
                TextView title = (TextView)findViewById(R.id.student_voucher_title_balance_text);
                title.setText("Collect Balance");
                //--
                Button button = (Button) findViewById(R.id.student_submit);
                button.setVisibility(View.GONE);
                //-
                button = (Button) findViewById(R.id.student_voucher_pay_cash);
                button.setVisibility(View.VISIBLE);
                //-
                button = (Button) findViewById(R.id.student_voucher_pay_bmf);
                button.setVisibility(View.VISIBLE);
            }
            else
            {
                TextView title = (TextView)findViewById(R.id.student_voucher_title_balance_text);
                title.setText("Balance");
                //--
                Button button = (Button) findViewById(R.id.student_submit);
                button.setVisibility(View.VISIBLE);
                //-
                button = (Button) findViewById(R.id.student_voucher_pay_cash);
                button.setVisibility(View.GONE);
                //-
                button = (Button) findViewById(R.id.student_voucher_pay_bmf);
                button.setVisibility(View.GONE);
            }
		}
	};
	
	private void CalculateCashBalance()
	{
		RadioButton btn = (RadioButton) findViewById(R.id.student_radio_red);
		if(btn.isChecked())
			cashBalance = totalFare - 0.75d;
		//--
		btn = (RadioButton) findViewById(R.id.student_radio_blue);
		if(btn.isChecked())
			cashBalance = totalFare - 0.55d;
		//--
		btn = (RadioButton) findViewById(R.id.student_radio_yellow);
		if(btn.isChecked())
			cashBalance = totalFare - 0.35d;
		//---
		TextView tv = (TextView)findViewById(R.id.student_textview_cash_balance);
		tv.setText(WorkingSession.getInstance().decimalFormat.format(cashBalance < 0? 0:cashBalance));
	}

    private View.OnClickListener onSubmitClick = new View.OnClickListener()
    {
        @Override
        public void onClick(View view)
        {
            CompletePayment(COMPLETE_PAYMENT_BY_VOUCHER, cashBalance);
        }
    };

    private View.OnClickListener onCollectCashClick = new View.OnClickListener()
    {
        @Override
        public void onClick(View view)
        {
            ShowCashCollectDialog();
        }
    };

    private View.OnClickListener onCollectBMFClick = new View.OnClickListener()
    {
        @Override
        public void onClick(View view)
        {
            if(WorkingSession.getInstance().currentPassenger.CurrentBalance < 0)
            {
                WorkingSession.getInstance().ShowErrorDialog(
                        StudentVoucher.this,
                        "Error",
                        "E-Card has INSUFFICIENT funds to Check In"
                );
                return;
            }
            CompletePayment(COMPLETE_PAYMENT_BY_BMF, cashBalance);
        }
    };

    private AlertDialog cashCollectDialog;
    protected void ShowCashCollectDialog()
    {
        AlertDialog.Builder builder;
        LayoutInflater inflater = (LayoutInflater) this
                .getSystemService(LAYOUT_INFLATER_SERVICE);
        //-
        View layout = inflater.inflate(R.layout.input_amount,
                (ViewGroup) findViewById(R.id.input_amount_root_view));

        //--
        TextView minAmount = (TextView) layout.findViewById(R.id.input_amout_min_text);
        minAmount.setText(String.format("(minimum %s)",
                WorkingSession.getInstance().decimalFormat.format(cashBalance))
        );
        //--
        Button cancel = (Button) layout.findViewById(R.id.input_amount_cancel);
        cancel.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                WorkingSession.getInstance().HideKeyboard(StudentVoucher.this);
                cashCollectDialog.cancel();
                finish();
            }
        });

        Button submit = (Button) layout.findViewById(R.id.input_amount_submit);
        submit.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                WorkingSession.getInstance().HideKeyboard(StudentVoucher.this);
                //--
                View root = v.getRootView();
                EditText inputAmountEdit = (EditText)root.findViewById(R.id.input_amount_value_edit);
                if(inputAmountEdit.getText().toString().trim().length() == 0)
                {
                    TextView error = (TextView) root.findViewById(R.id.input_amount_error_text);
                    error.setText("Please enter amount");
                    return;
                }

                double inputAmount = Double.parseDouble(inputAmountEdit.getText().toString().trim());
                if(inputAmount < cashBalance)
                {
                    TextView error = (TextView) root.findViewById(R.id.input_amount_error_text);
                    error.setText("Invalid amount");
                    return;
                }

                CompletePayment(COMPLETE_PAYMENT_BY_CASH, inputAmount);
                finish();
            }
        });

        builder = new AlertDialog.Builder(StudentVoucher.this);
        builder.setTitle("Collect Cash");
        builder.setCancelable(false);
        builder.setView(layout);
        cashCollectDialog = builder.create();

        cashCollectDialog.show();
    }

    public static final int COMPLETE_PAYMENT_BY_CASH = 1;
    public static final int COMPLETE_PAYMENT_BY_BMF = 2;
    public static final int COMPLETE_PAYMENT_BY_VOUCHER = 3;
    private void CompletePayment(int type, double amount)
    {
        Intent result = new Intent();
        result.putExtra("VOUCHER_DISCOUNT_AMOUNT", totalFare - cashBalance);
        String voucherType = activeVoucher.getId() == R.id.student_radio_red?"Red"
                :activeVoucher.getId() == R.id.student_radio_blue?"Blue"
                :activeVoucher.getId() == R.id.student_radio_yellow?"Yellow"
                :"Unknown";
        result.putExtra("VOUCHER_TYPE", voucherType);
        result.putExtra("VOUCHER_COLLECT_BALANCE_TYPE", type);
        switch (type)
        {
            case COMPLETE_PAYMENT_BY_VOUCHER:
                break;
            case COMPLETE_PAYMENT_BY_BMF:
                break;
            case COMPLETE_PAYMENT_BY_CASH:
                result.putExtra("VOUCHER_COLLECT_CASH", amount);
                break;
        }

        /*Intent result = new Intent();
        result.putExtra("VOUCHER_DISCOUNT_AMOUNT", totalFare - cashBalance);
        String voucherType = activeVoucher.getId() == R.id.student_radio_red?"Red"
                :activeVoucher.getId() == R.id.student_radio_blue?"Blue"
                :activeVoucher.getId() == R.id.student_radio_yellow?"Yellow"
                :"Unknown";
        result.putExtra("VOUCHER_TYPE", voucherType);
        setResult(RESULT_OK, result);
        finish();*/

        setResult(RESULT_OK, result);
        finish();
    }
}
